using System;
using System.Globalization;
using System.Xml.Linq;

namespace TwitterClient
{
	public class Tweet
	{
		public Tweet() { }
		
		public Tweet(XElement fromElement_)
		{
			if (fromElement_ == null)
				throw new ArgumentNullException("fromElement_");
			
			ParseUpdateElement(fromElement_);
		}
		
		public string UpdateText { get; set; }
		
		public DateTime PostedAt { get; set; }
		public string PostedBy { get; set; }
		
		private void ParseUpdateElement(XElement updateElement_)
		{
			if (updateElement_.Element("text") != null)
				UpdateText = updateElement_.Element("text").Value;
			
			if (updateElement_.Element("created_at") != null)
			{
				var parsedPostedAt = default(DateTime);
				
				if (DateTime.TryParseExact(updateElement_.Element("created_at").Value, 
				                           TWITTER_DATE_FORMAT, 
				                           CultureInfo.InvariantCulture, 
				                           DateTimeStyles.None,
				                           out parsedPostedAt))
				{
					PostedAt = parsedPostedAt;
				}
			}
			
			if (updateElement_.Element("user") != null)
			{
				var userElement = updateElement_.Element("user");
				
				if (userElement.Element("screen_name") != null)
					PostedBy = "@" + userElement.Element("screen_name").Value;
			}			
		}
				
		private const string TWITTER_DATE_FORMAT = "ddd MMM dd HH:mm:ss zzz yyyy";
	}
}
